package com.qinghe.pro.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.qinghe.utils.Page;

public class PageTag extends SimpleTagSupport {

	private Page page;

	private int pageRange = 10;

	@Override
	public void doTag() throws JspException, IOException {

		StringBuilder builder = new StringBuilder();
		createHtml(builder);
		createJs(builder);

		getJspContext().getOut().write(builder.toString());
	}

    private void createHtml(StringBuilder builder) {
		long begin = Math.max(1, page.getPageNum() - pageRange/2);
	    long end = Math.min(begin + (pageRange - 1), page.getTotalPage());

		builder.append("<div class=\"news-pagination\">\n");
		builder.append("<span class=\"info\">共" + page.getTotalCount() + "条数据，当前展示第1页</span>\n");
		builder.append("<nav>\n");
		builder.append("<ul class=\"pagination\">\n");
		
		if (page.getPageNum() != 1) {
			builder.append("<li><a href=\"javascript:void(0);\" onclick=\"gotoPage(" + (page.getPageNum() - 1) + ")\" aria-label=\"Previous\"><span aria-hidden=\"true\">上一页</span></a></li>\n");
	    } else {
			builder.append("<li><a class=\"grey\"><span aria-hidden=\"true\">上一页</span></a></li>\n");
	    }
	    for (long i = begin; i <= end; i++) {
	    	if (i == page.getPageNum()) {
	    		builder.append("<li class=\"active\"><a>" + i + "</a></li>\n");
	    	} else {
	    		builder.append("<li><a href=\"javascript:void(0);\" onclick=\"gotoPage(" + i + ")\">" + i + "</a></li>\n");
	    	}
	    }
	    if (page.getPageNum() == page.getTotalPage()) {
    		builder.append("<li><a class=\"grey\"><span aria-hidden=\"true\">下一页</span></a></li>\n");
	    } else {
    		builder.append("<li><a href=\"javascript:void(0);\" onclick=\"gotoPage(" + (page.getPageNum() + 1) + ")\" aria-label=\"Previous\"><span aria-hidden=\"true\">下一页</span></a></li>\n");
	    }
		
		builder.append("</ul>\n");
		builder.append("</nav>\n");
		builder.append("</div>\n");
    }

    private void createJs(StringBuilder builder) {
    	builder.append("<script type=\"text/javascript\">");
    	builder.append("function gotoPage(pageNum) {");
    	builder.append("    var form = document.getElementById(\"p_pagerForm\");");
    	builder.append("    document.getElementById(\"p_pageNum\").value = pageNum;");
    	builder.append("    form.submit();");
    	builder.append("}");
    	builder.append("</script>");
    }

	public void setPage(Page page) {
		this.page = page;
	}

	public void setPageRange(int pageRange) {
		this.pageRange = pageRange;
	}

}
